<template>
  <el-dialog 
    v-model="visible" 
    :title="query?.title" 
    width="1100" 
    draggable 
    :before-close="isClosed"
    class="custom-detail-dialog"
    :close-on-click-modal="false"
  >
    <el-skeleton :loading="loading" animated>
      <el-form 
        label-width="auto" 
        :model="formData" 
        ref="formRef" 
        :rules="pageData.rules" 
        :inline="true" 
        :size="size"
        class="detail-form"
      >   
        <el-form-item label="产品名称：" style="width: 30%" prop="product_name">
          <span class="form-value">{{ formData.product_name || '-----' }}</span>
        </el-form-item>
        <el-form-item label="供应商：" style="width: 30%" prop="supplierName">
          <span class="form-value">{{ formData.supplierName || '-----' }}</span>
        </el-form-item>
        <el-form-item label="产品类型：" style="width: 30%" prop="type">
          <span class="form-value">{{ formData.type ? translateType(formData.type) : '-----' }}</span>
        </el-form-item>
        <el-form-item label="款式或型号：" style="width: 30%" prop="brand_or_style">
          <span class="form-value">{{ formData.brand_or_style || '-----' }}</span>
        </el-form-item>
        <el-form-item label="内部型号：" style="width: 30%" prop="internal_brand">
          <span class="form-value">{{ formData.internal_brand || '-----' }}</span>
        </el-form-item>
        <el-form-item label="规格：" style="width: 30%" prop="specification">
          <span class="form-value">{{ formData.specification || '-----' }}</span>
        </el-form-item>
        <el-form-item label="产品重量：" style="width: 30%" prop="productWeight">
          <span class="highlight-number">
            {{ Number(formData.productWeight) }}<span class="unit">{{ formData.weightUnit }}</span>
          </span>
        </el-form-item>
        <el-form-item label="产品数量：" style="width: 30%" prop="productQuantity">
          <span class="highlight-number">
            {{ Number(formData.productQuantity) }}<span class="unit">{{ formData.quantityUnit }}</span>
          </span>
        </el-form-item>
        <el-form-item label="单价：" style="width: 30%" prop="unit_price">
          <span v-if="formData.unit_price" class="highlight-number">
            {{ Number(formData.unit_price).toFixed(2) }}<span class="unit">{{ formData.priceUnit }}</span>
          </span>
          <span v-else class="form-value">-----</span>
        </el-form-item>
        <el-form-item label="总价：" style="width: 30%" prop="productSum">
          <span v-if="formData.productSum" class="highlight-number total-price">
            {{ Number(formData.productSum).toFixed(2) }}<span class="unit">元</span>
          </span>
          <span v-else class="form-value">-----</span>
        </el-form-item>
        <el-form-item label="存量：" style="width: 30%" prop="stockLevel">
          <span v-if="(stockLevel.stock != null && stockLevel.stock != undefined) || (stockLevel.piece != null && stockLevel.piece != undefined )" class="highlight-number total-price">
            {{ Number(stockLevel.stock) }}<span class="unit">kg</span>&nbsp&nbsp&nbsp{{ Number(stockLevel.piece) }}<span class="unit">pcs</span>
          </span>
          <span v-else class="form-value">-----</span>
        </el-form-item>
        <el-form-item label="经济采购量：" style="width: 30%" prop="specification"> 
          <span class="form-value">{{ formData.idealNum || '-----' }}&nbspkg或pcs</span>
          <el-tooltip
          class="box-item"
          effect="dark"
          content="经济采购量需要填写订货成本与单位产品库存年维持费用率后才可显示"
          placement="bottom"
          >
          <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
        </el-tooltip>
        </el-form-item>
        <el-form-item label="商品描述：" style="width: 96%">
          <div class="description-content">
            <span>{{ formData.description || '-----' }}</span>
          </div>
        </el-form-item>
      </el-form>
    </el-skeleton>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isClosed" class="cancel-btn">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, reactive, toRefs, ref, PropType, watch } from 'vue'
import { purchaseDetails, purchaseEoq, inBound } from "../service/api"
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import pageData from '../service/pageService'

export default defineComponent({
  name: 'ProductDetailDialog',
  props: {
    query: {
      type: Object,
      default: () => ({})
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      visible: false,
      size: "large",
      stockLevel:{
        stock:  null,//重量
        piece: null,//数量
      },
      formData: {
        id: null,
        idealNum: null,
        type: null,
        product_name: null,
        brand_or_style: null,
        internal_brand: null,
        productQuantity: null,
        productWeight: null,
        priceUnit: null,
        weightUnit: null,
        quantityUnit: null,
        unit_price: null,
        productSum: null,
        description: null,
        supplierName: null,
        purchaseTime: null,
        specification: null,
      }
    })

    const formRef = ref<FormInstance>()
    
    const isClosed = () => {
      state.visible = false
      emit('viewData', state.visible)
    }

    const translateType = (val) => {
      if (val === 1) return "原料"
      else if (val === 2) return "产品"
      else return "其他"
    }
    //单位换算(计算EOQ用)
    const converseUnit = (row) =>{
    pageData.unitConversion.unitPrice = null
    pageData.unitConversion.amount = null
    pageData.unitConversion.piece = null
    if(row?.is_quantity_based == 0 && row?.priceUnit == "元/g"){
      pageData.unitConversion.unitPrice = row?.unit_price*1000
    }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/kg"){
      pageData.unitConversion.unitPrice = row?.unit_price
    }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/T"){
      pageData.unitConversion.unitPrice = row?.unit_price/1000
    }
    if(row?.is_quantity_based == 1 && row?.priceUnit == "元/pcs"){
      pageData.unitConversion.unitPrice = row?.unit_price
    }else if(row?.is_quantity_based == 1 && row?.priceUnit == "元/kpcs"){
      pageData.unitConversion.unitPrice = row?.unit_price/1000
    }
    if(row?.totalProductWeight && row?.weightUnit == "g"){
      pageData.unitConversion.amount = row?.totalProductWeight/1000
    }else if(row?.totalProductWeight && row?.weightUnit == "kg"){
      pageData.unitConversion.amount = row?.totalProductWeight
    }else if(row?.totalProductWeight && row?.weightUnit == "T"){
      pageData.unitConversion.amount = row?.totalProductWeight*1000
    }
    if(row?.totalProductQuantity && row?.quantityUnit == "pcs"){
      pageData.unitConversion.piece = row?.totalProductQuantity
    }else if(row?.totalProductQuantity && row?.quantityUnit == "kpcs"){
      pageData.unitConversion.piece = row?.totalProductQuantity*1000
    }
      console.log("单价",pageData.unitConversion.unitPrice)
      console.log("数量",pageData.unitConversion.piece)
      console.log("重量",pageData.unitConversion.amount)
    }
    const culculateEoq = () => {
      if(state.formData.activeIndex == 0 && props.query?.supplierId && props.query?.businessId){
        purchaseEoq(props.query?.supplierId,props.query?.businessId).then((res)=>{
          console.log("eoq.res",res.data)
          converseUnit(res.data)
          if(res.data.is_quantity_based == 0 && res.data.totalFee && res.data.costRate && res.data.validityPeriod ){
            let R = res.data.costRate/100
            let D = pageData.unitConversion.amount * (12/res.data.validityPeriod)
            state.formData.idealNum = Math.round(Math.sqrt((2 * D * res.data.totalFee) / (pageData.unitConversion.unitPrice * R)));
          }else if(res.data.is_quantity_based == 1 && res.data.totalFee && res.data.costRate ){
            let R = res.data.costRate/100
            let D = pageData.unitConversion.piece * (12/res.data.validityPeriod)
            state.formData.idealNum = Math.round(Math.sqrt((2 * D * res.data.totalFee) / (pageData.unitConversion.unitPrice * R)));
          }else {
            state.formData.idealNum = null
          }
        })
      }
    }
    // 封装判断isQuantityBased值的函数
    const getIsQuantityBased = (row) => {
        if( row?.type == 3 ) return 1;
        else if( row?.type == 2 ) return 0;
        else if( row?.type == 1 ) return 2;
    }
    const checkInventory = () => {
        if(!state.formData.product_name) ElMessage.warning("请先填写产品名称！")
        // else if(!state.formData.brand_or_style) ElMessage.warning("请先填写产品外部牌号或款式！")
        // else if(!state.formData.internal_brand) ElMessage.warning("请先填写产品内部牌号或款式！")
        else if(!state.formData.unit_price) ElMessage.warning("请先填写产品的单价")
        else if(!state.formData.type) ElMessage.warning("请先填写产品的类型")
        else if(state.formData.is_quantity_based == null || state.formData.is_quantity_based == undefined) ElMessage.warning("请先填写产品的计价方式")
        else {
          converseUnit(state.formData)
          let isQuantityBased = getIsQuantityBased(state.formData)
          const inBoundData = {
            skuName: state.formData.product_name,
            skuBrand: state.formData.brand_or_style?? "",
            internalBrand: state.formData.internal_brand?? "",
            specification: state.formData?.specification ?? "",
            unitPrice: pageData.unitConversion.unitPrice,
            byQuantity: isQuantityBased,
          }
          inBound(inBoundData).then((res)=>{
            state.stockLevel.stock= res.data.data.stock
            state.stockLevel.piece= res.data.data.piece
            console.log("inBoundData",res)
          })
        }
      }
    const initData = async () => {
      state.stockLevel = JSON.parse(JSON.stringify(pageData.initStockLevel))
      if(props.query?.type == 'view') {
          const params = {
            id:props.query?.id
          }
          purchaseDetails(params).then((res)=>{
            console.log('res',res)
            state.formData = res.data
            checkInventory()
            culculateEoq()
          }).catch((error) => {
            console.error('无法获取数据', error);
          });
        }
    }

    watch(() => props.dialogVisible, (val) => {
      state.visible = val
      if (val) initData()
    })

    onBeforeMount(() => {
      // 初始化逻辑
    })

    return {
      ...toRefs(state),
      isClosed,
      formRef,
      pageData,
      translateType
    }
  }
})
</script>

<style scoped>
/* 弹窗整体样式 */
.custom-detail-dialog {
  border-radius: 8px;
}

/* 弹窗标题样式 */
.custom-detail-dialog :deep(.el-dialog__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

.custom-detail-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 表单整体样式 */
.detail-form {
  padding: 20px;
}

/* 表单项样式 */
.detail-form :deep(.el-form-item) {
  margin-bottom: 18px;
  padding: 12px 16px;
  background: linear-gradient(120deg, #f9f9ff 0%, #f0f4ff 100%);
  border-left: 3px solid #409eff;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(228, 231, 237, 0.8);
}

.detail-form :deep(.el-form-item:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: rgba(64, 158, 255, 0.4);
  background: linear-gradient(to right, #ffffff 0%, #f8fbff 100%);
}

.detail-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  letter-spacing: 0.5px;
}

/* 奇数项和偶数项交替背景色 */
.detail-form :deep(.el-form-item:nth-child(odd)) {
  background: linear-gradient(to right, #ffffff 0%, #fafcff 100%);
}

.detail-form :deep(.el-form-item:nth-child(even)) {
  background: linear-gradient(to right, #ffffff 0%, #f6f9ff 100%);
}

/* 内容显示样式 */
.form-value {
  color: #333;
  font-size: 14px;
  display: inline-block;
  min-width: 100px;
}

/* 数值高亮样式 */
.highlight-number {
  font-weight: 600;
  color: #409eff;
}

.total-price {
  font-size: 16px;
  color: #f56c6c;
}

.unit {
  font-weight: normal;
  color: #666;
  font-size: 12px;
  margin-left: 2px;
}

/* 商品描述样式 */
.description-content {
  line-height: 1.6;
  padding: 8px;
  background: #f8f8f8;
  border-radius: 4px;
  white-space: pre-wrap;
  min-height: 60px;
  width: 100%;
}

/* 底部按钮样式 */
.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .custom-detail-dialog {
    width: 90% !important;
  }
  
  .detail-form :deep(.el-form-item) {
    width: 100% !important;
    margin-right: 0;
  }
}
</style>